package com.hhh.springai_test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhh.springai_test.common.ErrorCode;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.model.po.CommunityPost;
import com.hhh.springai_test.model.po.CommunityPostLike;
import com.hhh.springai_test.service.CommunityPostLikeService;
import com.hhh.springai_test.mapper.CommunityPostLikeMapper;
import com.hhh.springai_test.service.CommunityPostService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import java.util.stream.Collectors;

import java.util.Date;

/**
* @author 29915
* @description 针对表【community_post_like(帖子点赞表)】的数据库操作Service实现
* @createDate 2025-02-03 08:50:30
*/
@Service
public class CommunityPostLikeServiceImpl extends ServiceImpl<CommunityPostLikeMapper, CommunityPostLike>
    implements CommunityPostLikeService {

    @Resource
    private CommunityPostService communityPostService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean likeOrUnlike(Long postId, Long userId) {
        // 判断帖子是否存在
        CommunityPost post = communityPostService.getById(postId);
        if (post == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子不存在");
        }
        
        // 使用synchronized块来确保并发安全
        synchronized (String.format("post_like_%d_%d", postId, userId).intern()) {
            // 查询是否已经点赞
            QueryWrapper<CommunityPostLike> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("postid", postId)
                    .eq("userid", userId);
            
            CommunityPostLike postLike = this.getOne(queryWrapper);
            
            if (postLike != null) {
                // 已点赞则删除记录
                // 检查取消点赞后的总数是否合法
                if (post.getLikecount() <= 0) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "点赞数据异常");
                }
                
                boolean remove = this.removeById(postLike.getId());
                if (!remove) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "取消点赞失败");
                }
                
                post.setLikecount(post.getLikecount() - 1);
                boolean update = communityPostService.updateById(post);
                if (!update) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "取消点赞失败");
                }
                return false;
            } else {
                // 未点赞则新建记录
                CommunityPostLike newPostLike = new CommunityPostLike();
                newPostLike.setPostid(postId);
                newPostLike.setUserid(userId);
                boolean save = this.save(newPostLike);
                if (!save) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "点赞失败");
                }
                
                post.setLikecount(post.getLikecount() + 1);
                boolean update = communityPostService.updateById(post);
                if (!update) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "点赞失败");
                }
                return true;
            }
        }
    }

    @Override
    public Boolean isLiked(Long postId, Long userId) {
        QueryWrapper<CommunityPostLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("postid", postId)
                .eq("userid", userId);
        return this.count(queryWrapper) > 0;
    }

    @Override
    public Page<CommunityPost> getUserLikedPosts(Long userId, long current, long pageSize) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户id不合法");
        }
        if (current < 1 || pageSize < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页参数不合法");
        }
        
        // 分页查询用户的点赞记录
        Page<CommunityPostLike> likePage = new Page<>(current, pageSize);
        QueryWrapper<CommunityPostLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", userId)
                   .orderByDesc("createtime");
        
        Page<CommunityPostLike> likeRecords = this.page(likePage, queryWrapper);
        
        // 获取帖子id列表
        List<Long> postIds = likeRecords.getRecords().stream()
                .map(CommunityPostLike::getPostid)
                .collect(Collectors.toList());
        
        // 如果没有点赞记录，返回空页
        if (postIds.isEmpty()) {
            return new Page<CommunityPost>(current, pageSize);
        }
        
        // 查询帖子信息
        List<CommunityPost> posts = communityPostService.listByIds(postIds);
        
        // 创建新的Page对象并设置帖子信息
        Page<CommunityPost> postPage = new Page<>(current, pageSize);
        postPage.setRecords(posts);
        postPage.setTotal(likeRecords.getTotal());
        
        return postPage;
    }
}




